import 'package:flutter_device_info_plugin/flutter_device_info_plugin.dart';
import 'package:furaha_mkopo/cache/fm_cache.dart';
import 'package:furaha_mkopo/manager/fm_init_manager.dart';
import 'package:geolocator/geolocator.dart';

const String popLocationDate = "popLocationDate";

class FMLocationTool {

  static checkAccess() async {

    LocationPermission permission = await Geolocator.checkPermission();

    bool flag = FMInitManager().popLocation;
    if (permission == LocationPermission.denied || permission == LocationPermission.deniedForever) {
      if (flag && checkLocationTime) {
        FlutterDeviceInfoPlugin().showDeniedAccessAlert(
            "To offer you personalized loan options and services in your area, we need access to your location. Please enable location services for a tailored experience."
        );
      }
    }
  }
  
  static bool get checkLocationTime {
    FMCache cache = FMCache.getInstance();

    DateTime? latestDate = DateTime.tryParse(cache.get(popLocationDate) ?? '');

    DateTime nowTime = DateTime.now();

    if (latestDate != null) {
      DateTime aboveOneDay = latestDate.add(const Duration(days: 1));

      if (nowTime.isAfter(aboveOneDay)) {
        // 更新日期
        cache.setString(popLocationDate, nowTime.toIso8601String());
        return true;
      } else {
        return false;
      }
    }else {
      cache.setString(popLocationDate, nowTime.toIso8601String());
      return true;
    }

  }
}